import { local } from '@/utils';
import Request from '@/api/request'
import { RequestConfig } from '@/api/request/types'

// global base response interface 
// 返回统一格式
export interface baseResponse<T = any> {
  code: number,
  msg: string,
  flag: boolean,
  data: T
}

export interface baseRequest<T, R> extends RequestConfig<baseResponse<R>> {
  data?: T
}

const request = new Request({
  baseURL: process.env.NODE_ENV === 'development' ? import.meta.env.VITE_APP_DEV_URL : import.meta.env.VITE_APP_PROD_URL,
  timeout: 1000 * 60 * 5,
  interceptors: {
    // 请求拦截
    requestInterceptors: (config) => {
      const Authorization = local.get(import.meta.env.Authorization)
      if (typeof Authorization === 'string') {
        config.headers.Authorization = Authorization || ''
      }
      console.log('请求拦截', config);
      return config
    },
    // 响应拦截
    responseInterceptors: (config) => config
  }
})

// D为请求的数据 T为返回的data里边的数据
export const baseApi = <D, T = any>(config: baseRequest<D, T>) => {
  const { method = 'GET' } = config
  if (method.toUpperCase() === 'GET') {
    config.params = config?.data
  }
  return request.request<baseResponse<T>>(config)
}

export const cacncelRequest = (url: string | string[]) => {
  return request.cancelRequset(url)
}

export const cancelAllRequest = () => {
  return request.cancelAllRequest()
}
export * as login from './login/index'